<?php

namespace Respect\StackedViewRenderer;

class ViewRenderer
{

    protected $renderStack = array();
    protected $mimetypeHandler = null;

    public function __construct($dataContainer)
    {
        $this->dataContainer = $dataContainer;
    }

    public function appendInstances($instances)
    {
        foreach ($instances as $instance) {
            $this->append(
                '/' . str_replace('\\', '/', get_class($instance))
            );
        }
    }

    public function append($script)
    {
        $newItem = new ViewItem(
                $script,
                $this->dataContainer,
                $this->mimetypeHandler
        );
        $lastItem = end($this->renderStack);
        $topItem = reset($this->renderStack) ? : $newItem;
        if ($lastItem) {
            $lastItem->setChild($newItem);
        }
        $this->renderStack[] = $newItem;
        foreach ($this->renderStack as $item) {
            $item->setBottom($newItem);
        }
    }

    public function render()
    {
        foreach ($this->renderStack as $item) {
            $item->render();
        }
        echo reset($this->renderStack)->render();
    }

    public function setMimetypeHandler($handler)
    {
        $this->mimetypeHandler = $handler;
    }

}